﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

namespace UPNP.IO
{
    internal sealed class TcpIncomingResponse : TcpIncomingBase
    {
        private static readonly Regex HttpTcpStatusPattern = new Regex(@"^HTTP/[0-9\.]+ +([0-9]+).*$");

        public HttpStatusCode Status
        { 
            get; 
            private set;
        }

        private void ParseHttpStatus()
        {
            var httpStatusMatch = HttpTcpStatusPattern.Match(this.StatusHeader);

            if (!httpStatusMatch.Success)
            {
                throw new Exception("failed to parse HTTP status header: " + this.StatusHeader);
            }

            var httpStatusCode = int.Parse(httpStatusMatch.Groups[1].Value, TcpCulture);    // parse float for handling HTTP status sub codes like 401.3

            this.Status = (HttpStatusCode)httpStatusCode;
        }

        public TcpIncomingResponse(EndPoint sender, byte[] response)
            : base(sender, response)
        {
            Contract.Requires(sender != null);
            Contract.Requires(response != null);

            ParseHttpStatus();
        }

        public TcpIncomingResponse(EndPoint sender, string response)
            : base(sender, response)
        {
            Contract.Requires(sender != null);
            Contract.Requires(!string.IsNullOrEmpty(response));

            ParseHttpStatus();
        }
    }
}
